package cn.liuweiwei.service.impl;

import cn.liuweiwei.domain.Blog;
import cn.liuweiwei.domain.Tag;
import cn.liuweiwei.mapper.BlogAndTagMapper;
import cn.liuweiwei.mapper.BlogMapper;
import cn.liuweiwei.mapper.TagMapper;
import cn.liuweiwei.mapper.TypeMapper;
import cn.liuweiwei.service.TagService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private BlogAndTagMapper blogAndTagMapper;

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private TypeMapper typeMapper;

    @Override
    public PageInfo<Tag> findAllTagByPage(String pageNam, String pageSize) {
        PageHelper.startPage(parseString(pageNam), parseString(pageSize));
        List<Tag> tagList = initBlogCountByTagId();
        return new PageInfo<>(tagList);
    }

    @Override
    public Tag findBlogsByTagId(String id) {
        Tag tag = tagMapper.findOneById(id);
        List<String> blogIds = blogAndTagMapper.findBlogIdsByTagId(id);
        if (blogIds.size() == 0) {
            return tag;
        }
        List<Blog> blogList = blogMapper.findBlogsByIds(blogIds);
        for (Blog blog : blogList) {
            blog.setType(typeMapper.findOneById(blog.getTypeId()));
        }
        tag.setBlogList(blogList);
        return tag;
    }

    private List<Tag> initBlogCountByTagId() {
        List<Tag> tagList = tagMapper.findAll();
        for (Tag tag : tagList) {
            tag.setBlogCount(blogAndTagMapper.findBlogCountByTagId(tag.getId().toString()));
        }
        return tagList;
    }

    @Override
    public void insertOneTag(Tag tag) {
        tagMapper.insertOne(tag);
    }

    @Override
    public void updateOneTag(Tag tag) {
        tagMapper.update(tag);
    }

    @Override
    public void deleteById(String id) {
        tagMapper.deleteById(id);
    }

    @Override
    public List<Tag> findAllTag() {
        return initBlogCountByTagId();
    }

    private Integer parseString(String str) {
        return Integer.parseInt(str);
    }

}
